from django.core.mail import message, send_mail
from django.conf import Settings, settings
from django.http import HttpResponse
from django.template import loader
from django.template.loader import get_template
from datetime import datetime
from .models import Article, Videos, Kind, VideosKinds
from django.shortcuts import render, redirect, reverse
from .forms import ArticleForm, ContractForm

# Create your views here.

# 首页块状显示


def homepage(request):
    template = get_template('index.html')
    now = datetime.now()
    articles = Article.objects.all()
    # 侧边栏 热门文章
    hot_articles = articles.order_by('-read_count')[:5]
    # 侧边栏 最新文章
    archives = []
    for month in range(1, 13, 1):
        count = Article.objects.filter(
            post_datetime__year=2021, post_datetime__month=month).count()
        archives.append((month, count))
    # 侧边栏分类专栏
    kinds = Kind.objects.all()
    videos_kinds_name = VideosKinds.objects.all()
    article_kind_list = []
    for kind in kinds:
        count = Article.objects.filter(kind=kind).count()
        article_kind_list.append((kind, count))
    html = template.render(locals())
    return HttpResponse(html)

# 浏览次数


def show_article(requset, article_id):
    template = get_template('article.html')
    videos_kinds_name = VideosKinds.objects.all()
    article = Article.objects.get(article_id=article_id)
    try:
        article.read_count = article.read_count+1
        article.save()
    except:
        pass
    html = template.render(locals())
    return HttpResponse(html)

# 文章类型


def article_category(request, category):
    template = get_template('article_category.html')
    videos_kinds_name = VideosKinds.objects.all()
    category_articles = Article.objects.filter(category__exact=category)
    html = template.render(locals())
    return HttpResponse(html)

# 最新文章


def new_articles(request):
    template = get_template('new_articles.html')
    videos_kinds_name = VideosKinds.objects.all()
    new_articles = Article.objects.all().order_by('-post_datetime')[:10]
    html = template.render(locals())
    return HttpResponse(html)

# 增加文章


def add_article(request):
    if request.method == "POST":
        form = ArticleForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/')
    else:
        form = ArticleForm()
        videos_kinds_name = VideosKinds.objects.all()
        return render(request, 'add_article.html', locals())

    # if request.method == 'POST':
    #     article_id = request.POST.get('article_id', '')
    #     title = request.POST.get('title', '')
    #     content = request.POST.get('content', '')
    #     kind = request.POST.get('kind', '')
    #     if article_id and title and content and kind:
    #         result = Article(article_id=article_id,
    #                          title=title, content=content, kind=kind)
    #         result.save() #不可省略
    #         return redirect(reverse('home'))
    #     else:
    #         return HttpResponse("请填写完整的文章信息！")
    # videos_kinds_name = VideosKinds.objects.all()
    # return render(request, 'add_article.html', locals())

# 首页热门文章超链处理函数


def hot_articles(request):
    template = get_template('hot_articles.html')
    videos_kinds_name = VideosKinds.objects.all()
    hot_articles = Article.objects.all().order_by('-read_count')[:10]
    html = template.render(locals())
    return HttpResponse(html)

# 按月查看文章列表页面


def archives(request, year, month):
    template = get_template('archive.html')
    videos_kinds_name = VideosKinds.objects.all()
    articles = Article.objects.filter(
        post_datetime__year=year, post_datetime__month=month)
    months = range(1, 13)
    month = int(month)
    html = template.render(locals())
    return HttpResponse(html)

# 学习视频处理函数


def listvideos(request, slug):
    template = get_template('videos.html')
    # if slug == 'python':
    # video_list = [{
    #     'link': 'aid=4050443&bvid=BV1xs411Q799&cid=6534573',
    #     'name': '[小甲鱼]零基础入门学习Python'
    # },
    #     {
    #     'link': 'aid=90775300&bvid=BV1R7411F7JV&cid=155003866',
    #     'name': 'Python全套视频教程（700集）'
    # }]
    videos_kinds_name = VideosKinds.objects.all()
    video_list = Videos.objects.filter(kindname=slug)
    kind_name = VideosKinds.objects.get(id=slug)
    html = template.render(locals())
    return HttpResponse(html)

# 具体学习视频播放页面


def video(request, link, index='1'):
    template = get_template('video.html')
    videos_kinds_name = VideosKinds.objects.all()
    mv = Videos.objects.get(link=link)
    index = int(index)
    html = template.render(locals())
    return HttpResponse(html)

# 文章分类浏览


def kind(request, id):
    template = get_template('kind.html')
    videos_kinds_name = VideosKinds.objects.all()
    articles = Article.objects.filter(kind=id)
    kind_name = Kind.objects.get(id=id)
    html = template.render(locals())
    return HttpResponse(html)

# 视频选集


def select(request, slug, id):
    template = get_template('select.html')
    videos_kinds_name = VideosKinds.objects.all()
    videos = Videos.objects.filter(kindname=slug)
    video = videos.get(id=id)
    num = range(1, video.count_video+1)
    html = template.render(locals())
    return HttpResponse(html)

# 视频上一集


def up(request, link, index):
    index = int(index)
    up_index = index-1
    return redirect(reverse('video-url', args=(link, up_index)))

# 视频下一集


def down(request, link, index):
    index = int(index)
    down_index = index+1
    return redirect(reverse('video-url', args=(link, down_index)))

# 按文章标题搜索功能处理函数


def search_article(request):
    template = get_template('search_result.html')
    title = request.GET.get('title', '')  # title=request.GET['title']
    if title:
        articles = Article.objects.filter(title__contains=title)
        html = template.render(locals())
        return HttpResponse(html)
    return redirect('/')

# 发私信功能


def contract(request):
    if request.method == "POST":
        form = ContractForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            email = form.cleaned_data['email']
            message = form.cleaned_data['message']

            title = f'来自ssblog的网友{username}的意见'
            body = f'''
                姓名：{username}
                邮箱：{email}
                意见：{message}
            '''
            send_mail(title, body, settings.EMAIL_HOST_USER,
                      ['2995996695@qq.com'], fail_silently=False)
        return redirect('/')
    else:
        form = ContractForm()
        videos_kinds_name = VideosKinds.objects.all()
        return render(request, 'contract.html', locals())
